#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <arpa/inet.h>

#define PORT 2080
#define COUNT 500000
#define BREAK 20

const int killn = -1;

int main(int argc, char** argv)
{
	int sockfd, i, count, port, broadcast;
	struct sockaddr_in serv_addr;

	broadcast = 1;
	port = PORT;
	count = COUNT;
	
	if (argc < 2)
	{
		fprintf(stderr, "usage: %s Address [Port] [# packets]\n", argv[0]);
		exit(1);
	}


	if (argc > 2)
		port = atoi(argv[2]);

	if (argc == 4)
		count = atoi(argv[3]);

	if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0 )
	{
		fprintf(stderr, "Socket returned null\n");
		exit(2);
	}


	if (setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, &broadcast,
		sizeof(broadcast)) == -1)
	{
		perror("setsockopt (SO_BROADCAST)");
		exit(1);
	}

	printf("Count = %d, Port = %d\n", count, port);

	memset(&serv_addr, 0, sizeof(serv_addr));
	serv_addr.sin_family = AF_INET;
	serv_addr.sin_port = htons(port);
	serv_addr.sin_addr.s_addr = inet_addr(argv[1]);

	/* Not used in UDP
	if (connect(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
	{
		fputs("Connection error\n", stderr);
		exit(3);
	}
	*/
	
	for (i = 0; i < count; i++)
	{
		sendto(sockfd, &i, sizeof(int), 0, 
			(struct sockaddr *)&serv_addr, sizeof(struct sockaddr));
	}
	for (i = 0; i < BREAK; i++)
	{
		sendto(sockfd, &killn, sizeof(int), 0, 
			(struct sockaddr *)&serv_addr, sizeof(struct sockaddr));
	}

	close(sockfd);


	return 0;
}
